<?php
namespace app\common\model;

use think\Cache;
use think\Config;

class GetTui extends BaseModel{
	
	private $_appid = '8F60TPApIf9xkdSXY9pIa7';
	private $_appkey = 'v0V1FHOtBm73IUL8Yi8um3';
	private $_masterSecret = '3keBcYkPyQA06FoT1FDdQ';
	
    /**
     * 获取authtoken,从缓存中获取
     * 有效时间是1天，如果超时则重新获取
     * 为了保险起见，保存时间为23小时，超时刷新
     */
    public function getAuthToken(){
        $authToken=Cache::get('getui_auth_token');
        if($authToken){
            return $authToken;
        }else{
            $res=$this->refreshAuthToken();
            if($res['result']=='ok'){
                Cache::set('getui_auth_token',$res['auth_token'],82800);
                return $res['auth_token'];
            }
            return false;
        }
    }
	
    /**
     * 刷新或者初次获取 authtoken
     * 通过 restAPI刷新
     * protected 方法
     */
    protected function refreshAuthToken(){
        $timestamp=time()*1000;
        $sign=strtolower(hash('sha256',$this->_appkey.$timestamp.$this->_masterSecret,false));
        $dataArr=[
            'sign'=>$sign,
            'timestamp'=>$timestamp,
            'appkey'=>$this->_appkey,
        ];
        $content=json_encode($dataArr);
        $header=array(
            'Content-Type: application/json',
        );
        $url='https://restapi.getui.com/v1/'.$this->_appid.'/auth_sign';
        $res=$this->curl_post_json($url,$header,$content);
        $res=json_decode($res,true);
        return $res;
    }
    /**
     * 关闭鉴权
     */
    public function closeAuthToken(){
        $authToken=$this->getAuthToken();
        if(!$authToken){
            return false;
        }
        $header=[
            'Content-Type: application/json',
            'authtoken:'.$authToken
        ];
        $url='https://restapi.getui.com/v1/'.$this->_appid.'/auth_close';
        $res=$this->curl_post_json($url,$header);
        $res=json_decode($res,true);
        return $res;
    }
    /**
     *  向某个用户推送消息
     */
    public function sendToClient($user_id,$title='',$text='',$transmission_content=''){
		//查询用户是否存在
		if( intval( $user_id ) <= 0 ) return false;
		$user_info = db("user")->where(['user_id' => $user_id])->find();
		if( !$user_info ) return false;
		//写入系统消息
		db("system_message")->insert([
			'user_id' => $user_id,
			'type' => 1,
			'content' => $text,
			'create_time' => time()
		]);
		if( !$user_info['ge_cid'] ) return false;
        $authToken=$this->getAuthToken();
        $content=array(
            'message'=>[
                "appkey"=>$this->_appkey,
                "is_offline"=>false,
                "msgtype"=>"notification"
            ],
            'notification'=>[
                'style'=>[
                    'type'=>0,
                    'text'=>$text,
                    'title'=>$title
                ],
                "transmission_type"=> true,
                "transmission_content"=> $transmission_content
            ],
            "cid" => $user_info['ge_cid'],
            "requestid"=> "".time()
        );
        $content=json_encode($content);
        $header=array(
            'Content-Type: application/json',
            'authtoken:'.$authToken
        );
        $url='https://restapi.getui.com/v1/'.$this->_appid.'/push_single';
        $res=$this->curl_post_json($url,$header,$content);
        $res=json_decode($res,true);
        return $res;
    }
    /**
     * 群发消息
     * - 向所有的app发送透传消息
     */
    public function sendToAllTransmission($message){
        $authToken=$this->getAuthToken();
        $content=[
            'message'=>[
                "appkey"=>$this->_appkey,
                "is_offline"=>false,
                "msgtype"=>"transmission"
            ],
            'transmission'=>[
                "transmission_type"=>false,
                "transmission_content"=>$message,
            ],
            'requestid'=>"".time(),
        ];
        $content=json_encode($content);
        $header=[
            'Content-Type: application/json',
            'authtoken:'.$authToken
        ];
        $url='https://restapi.getui.com/v1/'.$this->_appid.'/push_app';
        //
        $res=$this->curl_post_json($url,$header,$content);
        $res=json_decode($res,true);
        return $res;
    }
    /**
     * 群发消息
     * - 向所有的app发送notification消息
     */
    public function sendToAllNotification($title='',$text='',$transmission_content=''){
        $authToken=$this->getAuthToken();
        $content=[
            'message'=>[
                "appkey"=>$this->_appkey,
                "is_offline"=>false,
                "msgtype"=>"notification"
            ],
            'notification'=>[
                'style'=>[
                    'type'=>0,
                    'text'=>$text,
                    'title'=>$title
                ],
                "transmission_type"=>true,
                "transmission_content"=>$transmission_content
            ],
            'requestid'=>"".time(),
        ];
        $content=json_encode($content);
        $header=[
            'Content-Type: application/json',
            'authtoken:'.$authToken
        ];
        $url='https://restapi.getui.com/v1/'.$this->_appid.'/push_app';
        //
        $res=$this->curl_post_json($url,$header,$content);
        $res=json_decode($res,true);
        return $res;
    }
	
	private function curl_post_json($url , $header = array() , $content = '') {
		$curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $res = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);
        }
        curl_close($curl);
        return $res;
	}
}